package com.netease.nie.controllers;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.netease.nie.base.cache.CacheParam;
import com.netease.nie.base.cache.DataOperation;
import com.netease.nie.base.cache.redis.RedisManager;
import com.netease.nie.base.controllers.BaseController;
import com.netease.nie.base.utils.CustomDateFormatUtils;
import com.netease.nie.base.utils.CustomWebUtils;
import com.netease.nie.base.utils.DateUtils;
import com.netease.nie.config.CreditGradeProperties;
import com.netease.nie.config.PresentGiftProperties;
import com.netease.nie.constants.BusinessConstants;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.constants.CreditHistoryChangeStants;
import com.netease.nie.constants.CreditHistoryOriginStants;
import com.netease.nie.dto.LoginLogoutDto;
import com.netease.nie.dto.UserLoginDto;
import com.netease.nie.model.Credit;
import com.netease.nie.model.CreditHistory;
import com.netease.nie.model.User;
import com.netease.nie.service.CreditService;
import com.netease.nie.service.GiftCreditService;
import com.netease.nie.service.UserService;
import com.netease.nie.utils.LogUtils;
import com.netease.nie.utils.UserLoginUtils;

/**
 * 用户登录接口
 * @author wwbn3695
 * @createDate July 23rd 2016
 *
 */
@RestController
@RequestMapping("/api/login")
public class UserLoginController extends BaseController {
	
	private Logger logger = Logger.getLogger(UserLoginController.class);

	private static final String USER_TOKEN_PREFIX = CachePrefixConstants.UserPrefix.USER_TOKEN_PREFIX;
	
	private static final String USER_CREDIT_PREFIX = CachePrefixConstants.UserPrefix.USER_CREDIT_PREFIX;
	
	private static final String USER_ACTIVATION_CODE_PREFIX = CachePrefixConstants.UserPrefix.USER_ACTIVATION_CODE_PREFIX;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CreditService creditService;
	
	@Autowired
	private GiftCreditService giftCreditService;
	
	@Autowired
	private PresentGiftProperties presentGiftProperties;
	
	@Autowired
	private CreditGradeProperties creditGradeProperties;
	
	@RequestMapping(value = "/callback", method = RequestMethod.POST, produces = "application/json")
	public String normalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		final UserLoginDto userLoginDto = UserLoginUtils.getUserLoginDto(request);
		if (userLoginDto == null)
			return jsonFail(BusinessConstants.USER_NOT_LOGIN.getCode(), BusinessConstants.USER_NOT_LOGIN.getMsg());
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		String userToken = UserLoginUtils.generateUserToken(userLoginDto);
		logger.warn("userToken = " + userToken);
		String userTokenKey = USER_TOKEN_PREFIX + userToken;
		List<String> keyList = Arrays.asList(userTokenKey);
		CacheParam cacheParam = new CacheParam();
		cacheParam.setKeyList(keyList);
		cacheParam.setPrefix(USER_TOKEN_PREFIX);
		DataOperation dataOperation = new DataOperation() {
			public Object operate() {
				return userService.queryUserIdBySsn(userLoginDto.getSsn());
			}
		};
		RedisManager redisManager = new RedisManager(cacheParam, dataOperation);
		Long userId = redisManager.passiveOperateCache(Long.class);
		logger.warn("userId = " + userId);
		Credit credit = null;
		boolean success = false;
		if (userId != null && userId > 0) {
			credit = creditService.queryUserCreditByUserId(userId);
			if (credit.getInit() == 0) {    // 如果上次没有初始化成功，则再次登录时重试
				initCredit(userId, userLoginDto.getSsn(), credit, redisManager, resultMap);
			} else {
				resultMap.put("init", 0);
				resultMap.put("user_id", userId);
			}
			success = true;
		} else {
			User user = generateUserByUserLoginDto(userLoginDto);
			userId = userService.registerUser(user);
			logger.warn("创建了用户id");
			if (userId != null && userId > 0) {
				credit = generateUserCredit(userId);
				creditService.insertUserCredit(credit);
				logger.warn("创建用户积分");
				initCredit(userId, userLoginDto.getSsn(), credit, redisManager, resultMap);
				success = true;
			}
		}
		
		if (success) {
			// 登录日志
			LoginLogoutDto loginLogoutDto = new LoginLogoutDto();
			loginLogoutDto.setAccountId(userLoginDto.getSsn());
			loginLogoutDto.setUserId(String.valueOf(userId));
			loginLogoutDto.setAccountVip(credit.getLevel());
			loginLogoutDto.setLeftPoint(credit.getCurrentCredit());
			loginLogoutDto.setExpirePoint(credit.getReadyToExpireCredit());
			loginLogoutDto.setIp(CustomWebUtils.getIp(request));
			
			LogUtils.logLogin(loginLogoutDto);
			
			return jsonSuccess(resultMap);
		} else {
			return jsonFail(BusinessConstants.USER_LOGIN_FAIL.getCode(), BusinessConstants.USER_LOGIN_FAIL.getMsg());
		}
	}
	
	private void initCredit(Long userId, String ssn, Credit credit, RedisManager redisManager, Map<String, Object> resultMap) {
		// 过去13个月
		
	}
	
	private User generateUserByUserLoginDto(UserLoginDto userLoginDto) {
		User user = new User();
		user.setSsn(userLoginDto.getSsn());
		user.setMobile(userLoginDto.getMobile());
		user.setUserName(userLoginDto.getSsn());
		user.setNickName("游戏热爱者" + RandomUtils.nextInt(99999));
		user.setCreateTime(Calendar.getInstance().getTimeInMillis());
		return user;
	}
	
	private Credit generateUserCredit(Long userId) {
		Credit credit = new Credit();
		credit.setUserId(userId);
		credit.setCurrentCredit(0);
		credit.setTotalGainCredit(0);
		credit.setLastYearHighestCredit(0);
		credit.setLevel(0);
		credit.setReadyToExpireCredit(0);
		credit.setTotalUseCredit(0);
		credit.setTotalExpireCredit(0);
		credit.setMaintainCredit(0);
		credit.setInit(0);
		credit.setModifyTime(0);
		return credit;
	}
	
	private CreditHistory generateCreditHistory(long userId, int giftCredit) {
		long currentTimeMills = DateUtils.currentTimeInMills();
		CreditHistory creditHistory = new CreditHistory();
		creditHistory.setChangeOriginStatus(CreditHistoryOriginStants.GIFT.getCode());
		creditHistory.setChangeStatus(CreditHistoryChangeStants.INCR.getCode());
		creditHistory.setCreateTime(currentTimeMills);
		creditHistory.setCredit(giftCredit);
		creditHistory.setUserId(userId);
		creditHistory.setGenerateDate(CustomDateFormatUtils.getyyyyMMddInt(currentTimeMills));
		String changeOriginDesc = "激活账号赠送奇遇点";
		creditHistory.setChangeOriginDesc(changeOriginDesc);
		return creditHistory;
	}

}
